<?php
namespace app\admin\controller;

use app\admin\library\Auth;
use think\Controller;
// use think\facade\Validate;
use think\facade\Session;

//每页显示的条数
define('LAYUI_PAGE', 1);
//每页条数的选择项
define('LAYUI_LIMIT', 10);
//账单类型-租金
define('TYPE_RENT', 'A');
//账单类型-电费
define('TYPE_ELECTRICITY', 'B');
//账单类型-水费
define('TYPE_WATER', 'C');
//账单类型-维修费
define('TYPE_FIX', 'D');
//账单类型-工资
define('TYPE_SALARY', 'E');
//账单类型-其他
define('TYPE_OTHER', 'F');

class Common extends Controller
{
    protected $auth;
    protected $checkLoginExclude = [];

    public function initialize()
    {
        if ($this->request->isPost()) {
            $token = $this->getToken();
            header('X-CSRF-TOKEN: ' . $token);
            if ($token !== $this->request->header('X-CSRF-TOKEN')) {
                $this->error('令牌已过期，请重新提交。');
            }
        }
        $this->auth = Auth::getInstance();
        $controller = $this->request->controller();
        $action = $this->request->action();
        if (in_array($action, $this->checkLoginExclude)) {
            return;
        }
        if (!$this->auth->isLogin()) {
            $this->error('您还没有登录。', 'Index/login');
        }
        if (!$this->auth->checkAuth($controller, $action)) {
            $this->error('您没有权限访问。');
        }
        if ($this->auth->isTimeOut()) {
            $this->error('您已超时，请重新登陆。');
        }
        $loginUser = $this->auth->getLoginUser();
        $this->assign('layout_login_user', ['id' => $loginUser['id'], 'username' => $loginUser['username'], 'expiration_date' => $loginUser['expiration_date']]);
        if (!$this->request->isAjax()) {
            $this->view->engine->layout('common/layout');
            $this->assign('layout_token', $this->getToken());
        }
    }

    public function getToken()
    {
        $token = Session::get('X-CSRF-TOKEN');
        if (!$token) {
            $token = md5(uniqid(microtime(), true));
            Session::set('X-CSRF-TOKEN', $token);
        }
        return $token;
    }

    public function returnLayui($data = [], $count = 0, $msg = '')
    {
        if (!$count) {
            $count = \count($data);
        }
        $data = [
            "code" => 0,
            "msg" =>  $msg,
            "count" => $count,
            "data" => $data
        ];
        return \json($data);
    }
}
